package com.venusj.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created By Administrator
 * User: VenusZ
 * Date: on 2020/3/23 21:28
 * Desc:
 */
@Component
public class MyLB implements LoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);


    public final int getAndIncrement() {
        int next;
        int current;
        do {
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
        } while (! this.atomicInteger.compareAndSet(current, next)); // cas  自旋锁
        System.out.println("*****第几次访问next:*****" + next);
        return next;
    }

    public ServiceInstance instance(List<ServiceInstance> serviceInstances) {
        int i = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(i);
    }
}
